//
//  LLHomeViewController.swift
//  新印象
//
//  Created by 魏延龙 on 2016/12/15.
//  Copyright © 2016年 魏延龙. All rights reserved.
//

import UIKit
import SnapKit
import Kingfisher
import MJRefresh


class LLHomeViewController: LLViewController,UITableViewDelegate,UITableViewDataSource,UIPopoverPresentationControllerDelegate,popVCDelegate {
    
    enum refreshStatus {
        case HEADER
        case FOOTER
    }
    
    var refresh = refreshStatus.HEADER
    var allData = [dataModel]()
    var tableView : UITableView?
    var maskView : popVC?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "新闻"
        self.navigationController?.tabBarItem.title = "NEWS"
        sessionrequest()
        loadUI()
    }
    
    func loadUI() {
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(homeViewControllerCell.classForCoder(), forCellReuseIdentifier: "homeViewControllerCell")
        self.tableView?.estimatedRowHeight = 270
        self.tableView?.rowHeight = UITableViewAutomaticDimension
        self.view.addSubview(self.tableView!)
        self.tableView?.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.refresh = refreshStatus.HEADER
            self.sessionrequest()
        })
        self.tableView?.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.refresh = refreshStatus.FOOTER
            self.sessionrequest()
        })
        
        
        let barButton = UIBarButtonItem(barButtonSystemItem:.add, target: self, action: #selector(listBarBtn(sender:)))
        self.navigationItem.rightBarButtonItem = barButton
    }
    func listBarBtn(sender:UIBarButtonItem) {
        print("点击了")
        maskView = popVC()
        maskView?.delegate = self
        maskView?.modalPresentationStyle = .popover
//        maskView = CGSize(width: 155, height: 300)
        maskView?.popoverPresentationController?.barButtonItem = sender
//        maskView?.sourceRect = view.bounds
//        maskView?.sourceView = view
        maskView?.popoverPresentationController?.permittedArrowDirections = .up
//        maskView?.backgroundColor = .red
        maskView?.popoverPresentationController?.delegate = self
        //弹出
        self.present(maskView!, animated: true) {
            
        }
    }
    // MARK: pop 的相关代理
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    
    func tableViewSelect(string: String) {
        if string == "扫一扫" {
            self.dismiss(animated: false, completion: {
                
            })
            let qrcode = LLQRcodeViewController()
            self.navigationController?.pushViewController(qrcode, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.allData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeViewControllerCell", for: indexPath) as! homeViewControllerCell
        let model = self.allData[indexPath.row]
        cell.contentTitle?.text = model.title
        cell.contentDesc?.text = model.desc
        cell.contentCtime?.text = model.ctime
        let url = URL(string: model.picUrl!)
        
        cell.contentImageView?.kf.setImage(with: url, placeholder: UIImage(named: "tree.jpg"))
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let urlviewController = LLUrlViewController()
        let url = self.allData[indexPath.row].url
        urlviewController.url = url
        self.navigationController?.pushViewController(urlviewController, animated: true)
    }
    
    func loadData() {
        
        // NSURLConnection
        let url = "http://apis.baidu.com/txapi/weixin/wxhot"
        let httpArg = "num=10"
        let req = NSMutableURLRequest(url: NSURL(string: url+"?"+httpArg) as! URL)
        req.timeoutInterval = 6
        req.httpMethod = "GET"
        req.addValue("89cf9afb83dc307b66e932a30c870fb7", forHTTPHeaderField: "apikey")
        NSURLConnection.sendAsynchronousRequest(req as URLRequest, queue: OperationQueue.main) { (response:URLResponse?, data:Data?, error:Error?) in
            if (error != nil) {
                print("请求错误")
                return
            }
            
            do{
                let con = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary<String, Any>
                print("解析json ：",con!["code"]!)
            }catch{
                print("解析失败")
            }
            
        }
        
    }
    
    func sessionrequest() {
        let url = "http://apis.baidu.com/txapi/weixin/wxhot"
        var httpArg = ""
        switch self.refresh {
        case .HEADER:
            httpArg = "num=10"
        case .FOOTER:
            let page = String(self.allData.count / 10 + 1)
            httpArg = "num=10&page=" + page
        }
        print("网络请求")
        let req = NSMutableURLRequest(url: NSURL(string: url+"?"+httpArg) as! URL)
        req.timeoutInterval = 6
        req.httpMethod = "GET"
        req.addValue("89cf9afb83dc307b66e932a30c870fb7", forHTTPHeaderField: "apikey")
        let session = URLSession.shared
        let task = session.dataTask(with: req as URLRequest) { (data:Data?, response:URLResponse?, error:Error?) in
            DispatchQueue.main.async {
                self.tableView?.reloadData()
                self.tableView?.mj_header.endRefreshing()
                self.tableView?.mj_footer.endRefreshing()
            }
            if (error != nil) {
                print("请求错误")
                return
            }
            do{
                switch self.refresh {
                case .HEADER:
                    self.allData.removeAll()
                case .FOOTER:
                    break
                }
                let con = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary<String, Any>
                if con!["errMsg"] != nil {
                    print("请求错误")
                    return
                }
                if (con!["msg"] as! String == "success") {
                    let dataArr = con!["newslist"]!
                     for dic in dataArr as! Array<Dictionary<String, Any>>{
                        let model = dataModel()
                        model.ctime = dic["ctime"] as! String?
                        model.title = dic["title"] as! String?
                        model.desc = dic["description"] as! String?
                        model.picUrl = dic["picUrl"] as! String?
                        model.url = dic["url"] as! String?
                        self.allData.append(model)
                    }
                    
                }
                
            }catch{
                print("解析失败")
            }
        }
        task.resume()
    }
    
}
class dataModel : NSObject{
    var ctime : String?
    var title : String?
    var desc : String?
    var picUrl : String?
    var url : String?
}
class homeViewControllerCell: UITableViewCell {
    var contentImageView : UIImageView?
    var contentTitle : UILabel?
    var contentDesc : UILabel?
    var contentCtime : UILabel?
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        loadUI()
    }
    
    func loadUI() {
        self.contentImageView = UIImageView()
        self.contentView.addSubview(self.contentImageView!)
        self.contentImageView?.snp.makeConstraints { (make) in
            make.top.equalTo(self.contentView).offset(5)
            make.left.equalTo(self.contentView).offset(5)
            make.right.equalTo(self.contentView).offset(-5)
            make.height.equalTo(230)
        }
        
        self.contentTitle = UILabel()
//        self.contentTitle?.lineBreakMode = .byWordWrapping
        self.contentTitle?.numberOfLines = 0
        
        self.contentView.addSubview(self.contentTitle!)
        self.contentTitle?.snp.makeConstraints({ (make) in
            make.top.equalTo((self.contentImageView?.snp.bottom)!).offset(5)
            make.left.equalTo(self.contentView).offset(5)
            make.right.equalTo(self.contentView).offset(-5)
        })
        
        self.contentDesc = UILabel()
        self.contentDesc?.font = UIFont.systemFont(ofSize: 12)
        self.contentView.addSubview(self.contentDesc!)
        self.contentDesc?.snp.makeConstraints({ (make) in
            make.top.equalTo((self.contentTitle?.snp.bottom)!).offset(5)
            make.left.equalTo(self.contentView).offset(5)
            make.bottom.equalTo(self.contentView).offset(-5)
        })
        
        self.contentCtime = UILabel()
        self.contentCtime?.font = UIFont.systemFont(ofSize: 12)
        self.contentView.addSubview(self.contentCtime!)
        self.contentCtime?.snp.makeConstraints({ (make) in
            make.top.equalTo((self.contentTitle?.snp.bottom)!).offset(5)
            make.left.equalTo((self.contentDesc?.snp.right)!).offset(10)
            make.bottom.equalTo(self.contentView).offset(-5)
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

protocol popVCDelegate {
    func tableViewSelect(string : String)
}

class popVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var tableView : UITableView?
    var delegate : popVCDelegate?
    let arrinfo = ["扫一扫","面对面","收钱吧","快来呀"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadUI()
        self.preferredContentSize = CGSize(width: 155, height: arrinfo.count * 44)
    }
    
    func loadUI() {
        tableView = UITableView(frame: self.view.frame, style: .plain)
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "pop")
        tableView?.bounces = false
        self.view.addSubview(tableView!)
        tableView?.dataSource = self
        tableView?.delegate = self
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrinfo.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "pop", for: indexPath)
        cell.textLabel?.text = arrinfo[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        delegate?.tableViewSelect(string: arrinfo[indexPath.row])
    }
    
}
